﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Hxsoft.AppV1.Module;

namespace Hxsoft.AppV1.Admin.ArticleManage
{
	public partial class ReleaseList : Hxsoft.AppV1.Page
	{
		#region property
		private int? _siteID;
		private bool isLoadSiteID = false;
		/// <summary>
		/// 当前的站点标识。
		/// </summary>
		protected int? SiteID
		{
			get
			{
				if (!isLoadSiteID)
				{
					// 读取当前站点信息，如果当前站点为指定的站点，则取当前站点值。
					int? currentSiteId = Sites.CurrentSiteId;
					if (currentSiteId.HasValue)
						_siteID = currentSiteId;
					else
					{
						string strSiteID = Request.QueryString["SiteID"];
						if (string.IsNullOrEmpty(strSiteID))
							_siteID = null;
						else
							_siteID = Convert.ToInt32(strSiteID);
					}
					isLoadSiteID = true;
				}
				return _siteID;
			}
		}


		private int? _moduleID;
		private bool _isLoadModuleID = false;
		/// <summary>
		/// 当前的模块标识。
		/// </summary>
		protected int? ModuleID
		{
			get
			{
				if (!_isLoadModuleID)
				{
					string strModuleID = Request.QueryString["ModuleID"];
					if (strModuleID == null)
						_moduleID = null;
					else
						_moduleID = Convert.ToInt32(strModuleID);
				}
				return _moduleID;
			}
		}

		/// <summary>
		/// 评论的信息类别
		/// </summary>
		public string InfoType
		{
			get
			{
				return Articles.INFO_TYPE;
			}
		}

		#endregion


		protected void Page_Load(object sender, EventArgs e)
		{
			if (ModuleArticles.GetManageListRight(ModuleID))
			{
				if (!IsPostBack)
				{
					LoadList();
					Page.DataBind();
				}
			}
			else
			{
				Messages.Add(new PageMessage(false, null, PageMessageType.Error, Res.PermissionExceptionMessageTitle, Res.PermissionExceptionMessage));
			}
		}

		protected void pager_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)
		{
			pager.CurrentPageIndex = e.NewPageIndex;
			LoadList();
		}

		protected void BtSearch_Click(object sender, EventArgs e)
		{
			pager.CurrentPageIndex = 1;
			LoadList();
		}

		protected void BtReload_Click(object sender, EventArgs e)
		{
			LoadList();
		}

		protected void List_ItemCommand(object source, RepeaterCommandEventArgs e)
		{
			ModuleArticleId identifier = GetListItemIdentifier(e.Item);
			string messages = "";

			switch (e.CommandName)
			{
				case "Delete":
					messages = Delete(identifier.ArticleId);
					break;
				case "Remove":
					messages = Remove(identifier);
					break;
				case "SetArticleEffectiveState":
					messages = SetArticleEffectiveState(identifier.ArticleId);
					break;
				case "SetModuleArticleEffectiveState":
					messages = SetModuleArticleEffectiveState(identifier);
					break;
				case "SetOpenComment":
					messages = SetOpenCommentState(identifier.ArticleId);
					break;
				case "SetRecommend":
					messages = SetRecommend(identifier);
					break;
				case "RemoveRecommend":
					messages = RemoveRecommend(identifier);
					break;
			}

			if (!String.IsNullOrEmpty(messages))
			{
				Messages.Add(new PageMessage(true, null, PageMessageType.Error, Res.OperationErrorTitle, messages));
			}

			LoadList();
		}

		protected void BtDelete_ServerClick(object sender, EventArgs e)
		{
			BatchOperate(CommandType.Delete);
		}

		protected void BtRemove_ServerClick(object sender, EventArgs e)
		{
			BatchOperate(CommandType.Remove);
		}		

		protected void BtCopy_Click(object sender, EventArgs e)
		{
			if (string.IsNullOrEmpty(hidIds.Value.ToString()))
				Messages.Add(new PageMessage(true, null, PageMessageType.Error, Res.OperationErrorTitle, "请选择目标模块!"));
			else
				BatchOperate(CommandType.Copy);
		}

		protected void BtCopyMove_Click(object sender, EventArgs e)
		{
			if (string.IsNullOrEmpty(hidIds.Value.ToString()))				
				Messages.Add(new PageMessage(true, null, PageMessageType.Error, Res.OperationErrorTitle, "请选择目标模块!"));
			else
				BatchOperate(CommandType.CopyMove);
		}

		protected void BtSetArticleEffectiveState_ServerClick(object sender, EventArgs e)
		{
			BatchOperate(CommandType.SetArticleEffectiveState);
		}

		protected void BtSetModuleArticleEffectiveState_ServerClick(object sender, EventArgs e)
		{
			BatchOperate(CommandType.SetModuleArticleEffectiveState);
		}

		protected void BtSetOpenCommentState_ServerClick(object sender, EventArgs e)
		{
			BatchOperate(CommandType.SetOpenCommentState);
		}

		/// <summary>
		/// 命令类别。
		/// </summary>
		protected enum CommandType
		{
			Delete,
			Remove,
			Copy,
			CopyMove,
			SetArticleEffectiveState,
			SetModuleArticleEffectiveState,
			SetOpenCommentState, 
			SetRecommend,
			RemoveRecommend
		}

		/// <summary>
		/// 批量操作。
		/// </summary>
		protected void BatchOperate(CommandType commandType)
		{
			ModuleArticleId identifier;			
			string messages = "";
			string messagesErr = "";

			foreach (RepeaterItem item in List.Items)
			{
				if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
				{
					CheckBox cbSelect = (CheckBox)item.FindControl("CbSelect");
					if (!cbSelect.Checked)
						continue;

					identifier = GetListItemIdentifier(item);
					string message = null;
					string message1 = null;
					string strMessage = null;

					switch (commandType)
					{
						case CommandType.Delete:
							message = Delete(identifier.ArticleId);
							break;
						case CommandType.Remove:
							message = Remove(identifier);
							break;
						case CommandType.Copy:
							strMessage = Copy(identifier);
							break;
						case CommandType.CopyMove:
							strMessage = CopyMove(identifier);
							break;
						case CommandType.SetArticleEffectiveState:
							message = SetArticleEffectiveState(identifier.ArticleId);
							break;
						case CommandType.SetModuleArticleEffectiveState:
							message = SetModuleArticleEffectiveState(identifier);
							break;
						case CommandType.SetOpenCommentState:
							message = SetOpenCommentState(identifier.ArticleId);
							break;
					}
					if (!String.IsNullOrEmpty(strMessage))
					{
						if (!String.IsNullOrEmpty(strMessage.Split("|")[0].ToString()))
							message = strMessage.Split("|")[0].ToString();
						if (!String.IsNullOrEmpty(strMessage.Split("|")[1].ToString()))
							message1 = strMessage.Split("|")[1].ToString();
					}

					if (!String.IsNullOrEmpty(message))
						messagesErr += "<li>[" + identifier.ToString() + "]" + message + "</li>";
					if(!String.IsNullOrEmpty(message1))
						messages += "<li>" + message1 + "</li>";
				}
			}
			if (!String.IsNullOrEmpty(messages))
			{
				Messages.Add(new PageMessage(true, null, PageMessageType.Prompt, Res.OperationCompleteTitle, messages));
			}
			if (!String.IsNullOrEmpty(messagesErr))
			{
				Messages.Add(new PageMessage(true, null, PageMessageType.Error, Res.OperationErrorTitle, messagesErr));
			}			

			LoadList();
		}

		/// <summary>
		/// 加载列表。
		/// </summary>
		protected void LoadList()
		{
			PaginationInfo<List<ModuleArticles.ModuleArticleForManageList>> pageInfo =
				ModuleArticles.GetPaginationManageList(ModuleID, IntExtensions.ParseOrNull(TbID.Text)
					, BooleanExtensions.ParseOrNull(DdlArticleIsEffective.SelectedValue)
					, BooleanExtensions.ParseOrNull(DdlModuleArticleIsEffective.SelectedValue)
					, TbUserName.Text
					, DateTimeExtensions.ParseOrNull(JtbStartRegisterDate.Text)
					, DateTimeExtensions.ParseOrNull(JtbEndRegisterDate.Text)
					, TbKeyword.Text
					, pager.PageSize, pager.CurrentPageIndex);

			pager.RecordCount = pageInfo.RecordCount;

			List.DataSource = pageInfo.Records;
			List.DataBind();

			pager.CustomInfoHTML = Helper.GetPagerCustomInfoHtml < List<ModuleArticles.ModuleArticleForManageList>>(pageInfo);
		}

		/// <summary>
		/// 取得 ListItem 的标识符。
		/// </summary>
		/// <param name="item">列表的 ListItem。</param>
		/// <returns>ListItem 的标识符。</returns>
		protected ModuleArticleId GetListItemIdentifier(RepeaterItem item)
		{
			ModuleArticleId identifier = new ModuleArticleId();
			HiddenField control;

			control = (HiddenField)item.FindControl("Identifier_ModuleID");
			identifier.ModuleId = Convert.ToInt32(control.Value);
			control = (HiddenField)item.FindControl("Identifier_ArticleID");
			identifier.ArticleId = Convert.ToInt32(control.Value);

			return identifier;
		}

		/// <summary>
		/// 删除指定的信息
		/// </summary>
		/// <param name="identifier">要删除信息的标识符。</param>
		/// <returns>如果删除发生错误则返回错误消息。</returns>
		protected string Delete(int identifier)
		{
			if (Articles.GetDeleteRight(Articles.GetItem(identifier)))
			{
				Articles.Delete(identifier);
				return null;
			}
			else
				return string.Format(Res.PermissionException_DeleteAppointedObject, identifier);
		}

		/// <summary>
		/// 移除指定的信息
		/// </summary>
		/// <param name="identifier">要移除信息的标识符。</param>
		/// <returns>如果移除发生错误则返回错误消息。</returns>
		protected string Remove(ModuleArticleId identifier)
		{
			if (ModuleArticles.GetRemoveRight(ModuleArticles.GetItem(identifier.ModuleId, identifier.ArticleId)))
			{
				ModuleArticles.Remove(identifier.ModuleId, identifier.ArticleId);
				return null;
			}
			else
				return string.Format(Res.PermissionException_DeleteAppointedObject, identifier.ModuleId + ":" + identifier.ArticleId);
		}

		/// <summary>
		/// 复制指定的信息到目标模块
		/// </summary>
		/// <param name="identifier">要移除信息的标识符</param>
		/// <returns></returns>
		protected string Copy(ModuleArticleId identifier)
		{
			string messageErr = "";
			string message = "";
			//向目标模块发布文章
			string[] mIDs = hidIds.Value.ToString().Split(",");
			ModuleArticle article = null;
			for (int i = 0; i < mIDs.Length - 1; i++)
			{
				article = new ModuleArticle();
				article.ArticleId = identifier.ArticleId;
				article.ModuleId = int.Parse(mIDs[i].ToString());
				if (ModuleArticles.GetReleaseRight(article))
				{
					if (ModuleArticles.Exists(article.ModuleId, article.ArticleId))
						message += "栏目 [" + article.ModuleId + "] 已经存在文章 [" + article.ArticleId + "]。";
					else
					{
						ModuleArticles.Release(article);
						message += "向栏目 [" + article.ModuleId + "] 发布文章 [" + article.ArticleId + "] 成功。";
					}
				}
				else
					messageErr += "您没有向栏目 [" + article.ModuleId + "] 发布文章  [" + article.ArticleId + "] 的权限。";
			}
			return messageErr + "|" + message;
		}

		/// <summary>
		/// 复制并移除指定信息
		/// </summary>
		/// <param name="identifier">要移除信息的标识符</param>
		/// <returns></returns>
		protected string CopyMove(ModuleArticleId identifier)
		{
			string messageErr = "";
			string message = "";
			string messages = null;
			//从当前摸块移除文章
			if (!string.IsNullOrEmpty(Remove(identifier)))
				messageErr += Remove(identifier);
			else
				messages=Copy(identifier);

			if (!String.IsNullOrEmpty(messages))
			{
				if (!String.IsNullOrEmpty(messages.Split("|")[0].ToString()))
					messageErr += messages.Split("|")[0].ToString();
				if (!String.IsNullOrEmpty(messages.Split("|")[1].ToString()))
					message += messages.Split("|")[1].ToString();
			}
			return messageErr + "|" + message;
		}

		/// <summary>
		/// 设置指定的信息的有效状态。
		/// </summary>
		/// <param name="identifier">要设置信息的标识符。</param>
		/// <returns>如果设置发生错误则返回错误消息。</returns>
		protected string SetArticleEffectiveState(int identifier)
		{
			if (Articles.GetSetEffectiveStateRight(Articles.GetItem(identifier)))
			{
				Articles.SetEffectiveState(identifier);
				return null;
			}
			else
				return string.Format(Res.PermissionException_SettingAppointedObject, identifier);
		}

		/// <summary>
		/// 设置指定的信息的发布状态。
		/// </summary>
		/// <param name="identifier">要设置信息的标识符。</param>
		/// <returns>如果设置发生错误则返回错误消息。</returns>
		protected string SetModuleArticleEffectiveState(ModuleArticleId identifier)
		{
			if (ModuleArticles.GetSetEffectiveStateRight(ModuleArticles.GetItem(identifier.ModuleId, identifier.ArticleId)))
			{
				ModuleArticles.SetEffectiveState(identifier.ModuleId, identifier.ArticleId);
				return null;
			}
			else
				return string.Format(Res.PermissionException_SettingAppointedObject, identifier.ModuleId + ":" + identifier.ArticleId);
		}

		/// <summary>
		/// 设置指定的信息的评论状态。
		/// </summary>
		/// <param name="identifier">要设置信息的标识符。</param>
		/// <returns>如果设置发生错误则返回错误消息。</returns>
		protected string SetOpenCommentState(int identifier)
		{
			if (Articles.GetSettingRight(Articles.GetItem(identifier)))
			{
				SetCommentState(identifier);
				//Article.SetOpenComment(identifier);
				return null;
			}
			else
				return string.Format(Res.PermissionException_SettingAppointedObject, identifier);
		}

		/// <summary>
		/// 获取评论状态
		/// </summary>
		/// <param name="articleID"></param>
		/// <returns></returns>
		protected string GetCommentState(int articleID)
		{
			InfoCommentState commentState = null;
			string strCommentState;
			if (IsExistComment(articleID, ref commentState))
			{
				strCommentState = (commentState.IsClose == false) ? "是" : "<span class=\"Emphasize\">否</span>";
			}
			else
			{
				strCommentState = "<span class=\"Emphasize\">否</span>";
			}
			return strCommentState;
		}

		/// <summary>
		/// 设置评论状态
		/// </summary>
		/// <param name="articleID"></param>
		protected void SetCommentState(int articleID)
		{
			InfoCommentState commentState = new InfoCommentState();
			commentState.InfoType = InfoType;
			commentState.InfoId = articleID.ToString();

			if (IsExistComment(articleID, ref commentState))
			{
				commentState.IsClose = !commentState.IsClose;
			}
			else
			{
				commentState.IsClose = false;
			}

			if (commentState != null)
			{
				InfoCommentStates.SetInfoCommentState(commentState.InfoType, commentState.InfoId, commentState.IsClose);
			}
		}

		protected string SetRecommend(ModuleArticleId identifier)
		{
			if (RecommendArticles.GetInsertRight(new RecommendArticle() { ArticleId = identifier.ArticleId, ModuleId = identifier.ModuleId }))
			{
				RecommendArticle reArticle = new RecommendArticle();
				reArticle.ArticleId = identifier.ArticleId;
				reArticle.ModuleId = identifier.ModuleId;
				reArticle.RecommendType =int.Parse(Dictionaries.GetItem(DicClasses.GetIdentifier(null,Module.Common.DivClassName_RecommendType).Value,Modules.GetCodeById(identifier.ModuleId)).Value);
				reArticle.CreationDate = DateTime.Now;
				reArticle.ModuleCode = Modules.GetCodeById(identifier.ModuleId);
				reArticle.SiteId = Modules.GetItem(identifier.ModuleId).SiteId;
				reArticle.IsEffective = false;

				RecommendArticles.Insert(reArticle);

				return null;
			}
			else
				return Res.PermissionExceptionMessage;
		}
		protected string RemoveRecommend(ModuleArticleId identifier)
		{
			if (RecommendArticles.GetDeleteRight(RecommendArticles.GetItem(identifier.ArticleId, identifier.ModuleId)))
			{
				RecommendArticles.Delete(identifier.ArticleId, identifier.ModuleId);
				return null;
			}
			else
				return string.Format(Res.PermissionException_DeleteAppointedObject, identifier.ArticleId);
		}

		/// <summary>
		/// 文章信息是否存在评论
		/// </summary>
		/// <param name="articleID"></param>
		/// <param name="commentState"></param>
		/// <returns></returns>
		protected bool IsExistComment(int articleID, ref InfoCommentState commentState)
		{
			string infoType = InfoType;
			InfoCommentState infoCommentState = InfoCommentStates.GetItem(infoType, articleID.ToString());
			if (infoCommentState != null)
			{
				commentState = infoCommentState;
				return true;
			}
			return false;
		}
		/// <summary>
		/// 是否已经推荐
		/// </summary>
		protected bool IsExistRecommend
		{
			get {
				int articleId = int.Parse(Convert.ToString(Eval("ArticleId")));
				int moduleId = int.Parse(Convert.ToString(Eval("ModuleId")));
				return RecommendArticles.Exists(articleId, moduleId);
			}
		}
		/// <summary>
		/// 是否显示推荐按钮
		/// </summary>
		protected bool IsShowRecommendButton		
		{
			get {
				if (!ModuleID.HasValue) return false;

				return Dictionaries.Exists(DicClasses.GetIdentifier(null,Module.Common.DivClassName_RecommendType).Value,Modules.GetCodeById(ModuleID.Value));
			}
		}
	}
}
